package com.sundog.sundroid;

import java.util.HashMap;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.Toast;

import com.sundog.sundroid.google.GoogleService;
import com.sundog.sundroid.google.SheetInfo;

public class Login extends Activity implements OnClickListener {
	
	public static String user;
	public static String id;
	public static String usersNames[];
	public static String storyNames[];
	public static String pass;
	public static String SpreadId;
	private String message = "";
	private String auth_token = "";
	private String username = "";
	static Map<String, String> sheets;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login);
        
        // Set up click listeners for buttons
        View continueButton = this.findViewById(R.id.ok_button);
        continueButton.setOnClickListener(this);
        View newButton = this.findViewById(R.id.cancel_button);
        newButton.setOnClickListener(this);
    }
    
    public void onClick(View v) {
    	switch (v.getId()) {
    	case R.id.ok_button:
    		if (clickSign()) {
    			openSelectSpreadsheetDialog();
    		}
    		break;
    	case R.id.cancel_button:
    		finish();
    		break; 		
    	}
    }
    
    private boolean clickSign() {
        username = ((EditText)this.findViewById(R.id.username_text)).getText().toString();
        String password = ((EditText)this.findViewById(R.id.password_text)).getText().toString();

        user = username;
        pass = password;
        
        try {
            String googleAccountUrl = "https://www.google.com/accounts/ClientLogin";

            HttpClient httpclient = new DefaultHttpClient();
            Map<String, String> params = new HashMap<String, String>();
            params.put("accountType", "HOSTED_OR_GOOGLE");
            params.put("Email", username);
            params.put("Passwd", password);
            params.put("service", "wise");
            params.put("source", "sundog-sundroid-0.9");

            HttpPost post = new HttpPost(encodeParamsToUrl(googleAccountUrl, params));
            post.setHeader("Content-Type", "application/x-www-form-urlencoded");

            HttpResponse res = httpclient.execute(post);
            StatusLine status = res.getStatusLine();

            if (status.getStatusCode() == HttpStatus.SC_OK) {
            	auth_token = GoogleService.extractTokenFromResponse("Auth", res.getEntity().getContent());
                return true;
            } else if (status.getStatusCode() == HttpStatus.SC_FORBIDDEN) {
            	message = GoogleService.convertResponseToString(res.getEntity().getContent());
                Log.w("Status Code = " + HttpStatus.SC_FORBIDDEN, message);
                Toast.makeText(Login.this, "Cannot log in for the following reason: \n" + GoogleService.explainErrorCode(message), Toast.LENGTH_LONG).show();
            } 
        } catch (Exception e1) {
            Log.e("Login Failed", e1.toString(), e1);
        }
        return false;
    }

    private String encodeParamsToUrl(String url, Map<String, String> params) {
        StringBuilder builder = new StringBuilder(url);
        boolean first = true;
        for (String key: params.keySet()) {
            if (first) {
                builder.append("?");
                first = false;
            } else {
                builder.append("&");
            }
            builder.append(key).append("=").append(params.get(key));
        }
        return builder.toString();
    }
    
    private void openSelectSpreadsheetDialog() {
    	sheets = GoogleService.getSpreadsheets(auth_token);
    	String[] sheetNames = sheets.keySet().toArray(new String[sheets.size()]);
    	
    	new AlertDialog.Builder(this)
    		.setTitle(R.string.select_spreadsheet_title)
    		.setItems(sheetNames,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialoginterface, int i) {
						id = sheets.get(sheets.keySet().toArray()[i]);
						startGame();
					}
    		})
    		.show();
    	
    }
   
    private void startGame() {
    	Log.d("Spreadsheet selected", "ID " + id);
    	id = id.replace("http://spreadsheets.google.com/feeds/spreadsheets/private/full/", "");
    	SpreadId = id;
    	
    	Map<String, String> users = GoogleService.returnMod(id);
    	 usersNames = users.keySet().toArray(new String[users.size()]);
    	Log.d("USERNAME[0]", usersNames[0]);
    	Log.d("This Users Login Id", username );
    	if (username.equals(usersNames[0])){
    		Log.d("MOD WORK?", "TRUE");
    		Intent j = new Intent(this, scrumMaster.class);
    		
    		startActivity(j);
    	}
    	else {
    		Log.d("MOD WORK?", "FALSE");
    		Map<String, String> storys = GoogleService.returnStorys(id);
    	    storyNames = storys.keySet().toArray(new String[storys.size()]);
    	    
    	  
        	for(int i=0; i<=storyNames.length-1; i++) {
    			Log.d("StoryName" , "Name = " + storyNames[i]);	
			}
        	
        	// Create the intent and add the extras
    		Intent i = new Intent(this, Wait.class);
    		

    		startActivity(i);
    	}
    } 
}